package com.example.demo.leetcode100题;

import com.example.demo.StopWatchTemplate;

/**
 * @author：zzc
 * @date: 2022/9/1
 */
public class 回文链表 {

    //给你一个单链表的头节点 head ，请你判断该链表是否为回文链表。如果是，
    //返回 true ；否则，返回 false 。
    //示例 1：
    //输入：head = [1,2,2,1]
    //输出：true
    //示例 2：
    //输入：head = [1,2]
    //输出：false
    //提示：
    //链表中节点数目在范围[1, 105
    //] 内
    //0 <= Node.val <= 9
    //进阶：你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题？

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        node1.next = new ListNode(2);
        node1.next.next = new ListNode(2);
        node1.next.next.next = new ListNode(1);

        System.out.println(StopWatchTemplate.doSupplier(() -> isPalindrome(node1)));
    }

    public static boolean isPalindrome(ListNode head) {
        if (head == null) {
            return true;
        }

        // 找到前半部分链表的尾节点并反转后半部分链表
        ListNode firstHalfEnd = endOfFirstHalf(head);
        ListNode secondHalfStart = reverseList(firstHalfEnd.next);

        // 判断是否回文
        ListNode p1 = head;
        ListNode p2 = secondHalfStart;
        boolean result = true;
        while (result && p2 != null) {
            if (p1.val != p2.val) {
                result = false;
            }
            p1 = p1.next;
            p2 = p2.next;
        }

        // 还原链表并返回结果
        firstHalfEnd.next = reverseList(secondHalfStart);
        return result;
    }

    private static ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }

    private static ListNode endOfFirstHalf(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }


    private static ListNode reverseLinkedList(ListNode head) {
        ListNode pre = null, cur = head;
        while (cur != null) {
            // 将下一个节点暂存
            ListNode t = cur.next;
            // 将下一个节点指向前一个节点
            cur.next = pre;
            // 将当前节点当作前一个节点
            pre = cur;
            //cur往下遍历
            cur = t;
        }
        return pre;
    }

}
